<template>
  <div v-if="!isMain && isDetail" class="view-plan-detail">
    <px-scrollbar ref="scrollbarRef" class="view-plan-detail-content pr-[10px]" @scroll="handleScroll">
      <div class="view-plan-detail-top" :class="{ 'mb-[20px]': [1, 2, 4].indexOf(detailData.planStatus) !== -1 }">
        <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
        <div class="view-plan-detail-top-title">
          {{ detailData.planName }}
        </div>
        <px-tag class="ml-[16px]" :type="tagArr[detailData['planStatus']]">{{ detailData["planStatusDesc"] }}</px-tag>
        <px-button
          v-if="!((detailData['planStatus'] === 3 && detailData['execType'] == 1) || detailData['planStatus'] === 4)"
          type="primary"
          class="view-plan-detail-top-edit"
          @click="editPlan"
          >修改计划</px-button
        >
      </div>
      <CustomTabs
        v-if="detailData.planStatus == 3 || detailData.planStatus == 4"
        :tabList="tabList"
        :activeName="activeName"
        style="margin-bottom: 12px"
        @tabSelect="handelTabSelected"
      />
      <div v-show="activeName === 'first'">
        <div ref="basicsRef" class="view-plan-title">基本信息</div>
        <div class="view-plan-wrap">
          <div class="view-plan-content">
            <div class="view-plan-item">
              <div class="label">巡检计划编号</div>
              <div class="text">{{ detailData.planNo }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">地块</div>
              <div class="text">{{ detailData.factoryAreaDesc }}</div>
            </div>
          </div>

          <div class="view-plan-content">
            <div class="view-plan-item">
              <div class="label">任务分配</div>
              <div class="text">{{ detailData.checkGroupDesc }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">建议工作天数</div>
              <div class="text">{{ detailData.recommendDay }}</div>
            </div>
          </div>
          <div class="view-plan-content">
            <div class="view-plan-item plus">
              <div class="label">说明</div>
              <div class="text">{{ detailData.description }}</div>
            </div>
          </div>
        </div>
        <div ref="contentRef" class="view-plan-title">巡检内容</div>
        <div class="view-plan-wrap">
          <div class="view-plan-content">
            <div class="view-plan-item plus">
              <div class="label">巡检区域</div>
              <div class="text">
                <px-tag v-for="(item, index) in checkAreaDescArr" :key="index" class="ml-2" type="info">{{ item }}</px-tag>
              </div>
            </div>
          </div>
          <div class="view-plan-content">
            <div class="view-plan-item plus">
              <div class="label">巡检内容</div>
              <div class="text">
                {{ dealCheckTypeName(detailData.checkType) }}
              </div>
            </div>
          </div>
        </div>
        <div class="view-plan-wrap noborder">
          <div class="view-plan-content">
            <InspectRulesTable :table-data="tableData" :tableColumns="tableColumns" :total="0" class="w-[100%]" />
          </div>
        </div>
        <div ref="periodRef" class="view-plan-title">执行周期</div>
        <div class="view-plan-wrap">
          <div class="view-plan-content">
            <div class="view-plan-item">
              <div class="label">执行方式</div>
              <div class="text">{{ ["", "固定时间", "周期时间"][detailData.execType] }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">开始时间</div>
              <div class="text">{{ detailData.execStartDate }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">结束时间</div>
              <div class="text">{{ detailData.execEndDate }}</div>
            </div>
          </div>
          <template v-if="detailData.execType == 2">
            <div class="view-plan-content">
              <div class="view-plan-item plus">
                <div class="label">排查周期</div>
                <div v-if="['DAY', 'WEEK', 'MONTH'].includes(detailData.cyclePerUnit)" class="text">
                  {{ dealExecTime() }}
                  <px-tag v-for="item in weeks" :key="item" class="ml-[6px]" type="info">{{ item }}</px-tag>
                  <px-tag v-for="item in days" :key="item" class="ml-[6px]" type="info">{{ item }}</px-tag>
                </div>
                <div v-else class="text">
                  {{ dealExecTime() }}
                  <px-tag v-for="item in months" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                  的
                  <px-tag v-for="item in days" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                  日
                </div>
              </div>
            </div>
            <div class="view-plan-content">
              <div class="view-plan-item">
                <div class="label">任务执行时间</div>
                <div class="text">
                  <px-tag v-for="item in operates" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                </div>
              </div>
              <div class="view-plan-item">
                <div class="label">执行时长</div>
                <div class="text">{{ `${detailData.execDuration}${unitList[detailData.execDurationUnit]}` }}</div>
              </div>
              <div class="view-plan-item">
                <div class="label">宽泛期</div>
                <div class="text">{{ `${detailData.extendDuration}${unitList[detailData.extendDurationUnit]}` }}</div>
              </div>
            </div>
            <div class="view-plan-content">
              <div class="view-plan-item">
                <div class="label">
                  <ReTextTooltip content="任务生成并提醒时间" />
                </div>
                <div class="text">{{ taskList[detailData.taskCreateTime] }}</div>
              </div>
              <div class="view-plan-item large">
                <div class="label">
                  <ReTextTooltip content="立即生成第一次巡检任务（后续巡检任务依照任务生成时间生成）" />
                </div>
                <div class="text">{{ detailData.createTaskImmediately === 1 ? "是" : "否" }}</div>
              </div>
            </div>
          </template>
        </div>

        <div
          ref="equipRef"
          class="view-plan-title"
          v-if="!(detailData.checkType && detailData.checkType.length == 1 && detailData.checkType[0] === 'environment')"
        >
          巡检设备
        </div>
        <div
          class="view-plan-wrap noborder"
          v-if="!(detailData.checkType && detailData.checkType.length == 1 && detailData.checkType[0] === 'environment')"
        >
          <div class="view-plan-content">
            <InspectRulesTable :table-data="tableEqiupSelected" :tableColumns="tableEqiupColums" :total="0" class="w-[100%]" />
          </div>
        </div>
      </div>

      <div v-show="activeName === 'second'">
        <px-table row-key="id" :data="taskTable" class="inspect-table" size="small" height="calc(100vh - 311px)" border>
          <px-table-column type="index" align="center" min-width="60" fixed="left" />
          <template v-for="(item, index) in taskTableColumns" :key="index">
            <px-table-column
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template v-if="item.prop === 'taskType'" #default="scope">
                <div v-if="scope.row.taskStatusDesc" class="status">
                  <div class="circle" :style="{ backgroundColor: `${TAG_CONFIG[scope.row.taskStatus]?.color}` }" />
                  <p :style="{ color: `${TAG_CONFIG[scope.row.taskStatus]?.color}` }">{{ scope.row.taskStatusDesc }}</p>
                </div>
                <span v-else>-</span>
              </template>

              <template v-else #default="scope">{{
                scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
              }}</template>
            </px-table-column>
          </template>

          <px-table-column fixed="right" label="操作" min-width="180" align="center">
            <template #default="scope">
              <px-tooltip content="详情" placement="top">
                <px-button link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="inspection-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </px-scrollbar>
    <WidgetRouter v-show="activeName == 'first'" :router-list="routerList" :scrollbar-ref="scrollbarRef" :scroll-top="scrollTop" />
  </div>
</template>
<script setup lang="ts">
import ReTextTooltip from "@/components/ReTextTooltip";
import CustomTabs from "@/components/Tabs/index.vue";
import { onBeforeMount, ref, watch } from "vue";
import { WidgetRouter } from "../../components/index";
import { TableItem } from "../../types";
import InspectRulesTable from "./InspectRulesTable.vue";

import { getByPlanNo } from "@/api/erc/inspectPlan";
import { queryTaskTable } from "@/api/erc/inspectTask";
import { cloneDeep, debounce } from "@pureadmin/utils";
import { TAG_CONFIG } from "../../task/config";

import { useRouter } from "vue-router";

const router = useRouter();
const isView = ref(false);
const isMain = defineModel("isMain");
const isDetail = defineModel("isDetail");
const planNo = defineModel("planNo");
const isAdd = defineModel("isAdd");
const isUpdate = defineModel("isUpdate");
//右侧滚动导航
const scrollbarRef = ref(null);
const routerList = ref([]);
const scrollTop = ref();
//定位ref
const basicsRef = ref(null);
const contentRef = ref(null);
const periodRef = ref(null);
const equipRef = ref(null);

const tabList = ref([
  {
    name: "first",
    label: "巡检计划"
  },
  {
    name: "second",
    label: "巡检任务"
  }
]);
const activeName = ref("first");
// 巡检规则table
const tableData = ref([]);
//选择设备table
const tableEqiupSelected = ref([]);
//巡检任务table
const taskTable = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  planNo: ""
});

const detailDataTmpl = {
  planNo: "",
  planName: "",
  planStatus: 0, //1-草稿,2-未开始,3-进行中,4-已完成
  execType: 1, //执行方式 1-固定时间,2-周期时间
  execStartDate: "",
  execEndDate: "",
  execDuration: 0,
  execDurationUnit: "HOUR",
  extendDuration: 0,
  extendDurationUnit: "HOUR",
  factoryAreaCode: "",
  checkArea: "",
  checkGroupCode: "",
  cyclePerNum: 0,
  cyclePerUnit: "DAY",
  cycleValue: "",
  cycleTime: "",
  taskCreateTime: "",
  description: "",
  eqpRelationList: [],
  checkRuleNos: [],
  checkType: []
};
const detailData = ref(cloneDeep(detailDataTmpl));
const weeksMap = {
  MONDAY: "星期一",
  TUESDAY: "星期二",
  WEDNESDAY: "星期三",
  THURSDAY: "星期四",
  FRIDAY: "星期五",
  SATURDAY: "星期六",
  SUNDAY: "星期日"
};
const monthArr = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);
const operateTimeArr = Array.from({ length: 24 }, (_, i) => (i < 10 ? `0${i}:00` : `${i}:00`));
const unitList = {
  DAY: "日",
  HOUR: "小时"
};
const taskList = ["", "准点生成", "提前10分钟", "提前30分钟", "提前1小时", "提前1天"];
const weeks = ref([]);
const days = ref([]);
const months = ref([]);
const operates = ref([]);

const checkAreaDescArr = ref([]);
const tagArr = ["", "info", "warning", "", "danger"];
const checkTypeArr = { equipment: "设备巡检", environment: "环境巡检" };
const dealCheckTypeName = checkType => {
  if (!checkType || !checkType.length) return "";
  return checkType.reduce((acc, cur) => {
    if (!acc) return checkTypeArr[cur];
    return acc + "," + checkTypeArr[cur];
  }, "");
};
const tableColumns = ref<TableItem[]>([
  { prop: "expend", minWidth: "55", fixed: "left" },
  { prop: "checkRuleNo", label: "规则编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "checkRuleName", label: "巡检规则名称", minWidth: "160", showOverflowTooltip: true },
  { prop: "facName", label: "地块", minWidth: "160", showOverflowTooltip: true },
  { prop: "eqpTypeName", label: "设备类型/巡检区域", minWidth: "160", showOverflowTooltip: true },
  { prop: "ruleTypeName", label: "规则类型", minWidth: "160", showOverflowTooltip: true }
  // { prop: "recommendDay", label: "建议工作天数", minWidth: "160", showOverflowTooltip: true }
]);

const tableEqiupColums = ref<TableItem[]>([
  { prop: "index", minWidth: "55", fixed: "left" },
  { prop: "eqpId", label: "设备编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "eqpName", label: "设备名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  {
    prop: "typeNameAll",
    label: "设备系统",
    minWidth: "160",
    showOverflowTooltip: true,
    customFun: row => {
      if (row) {
        const strArr = row.split("/");
        if (strArr.length > 1) {
          strArr.pop();
          if (strArr.length > 1) {
            return strArr.join("/");
          } else {
            return strArr.join("");
          }
        } else {
          return row;
        }
      } else {
        return "-";
      }
    }
  },
  { prop: "typeName", label: "设备类型", minWidth: "160", showOverflowTooltip: true },
  { prop: "specification", label: "设备型号", minWidth: "160", showOverflowTooltip: true },
  { prop: "positionNameAll", label: "安装位置", minWidth: "160", showOverflowTooltip: true }
]);
const taskTableColumns = ref<TableItem[]>([
  { prop: "taskNo", label: "任务(工单)编号", minWidth: "240", showOverflowTooltip: true, fixed: "left" },
  { prop: "planNo", label: "所属计划编号", minWidth: "200", showOverflowTooltip: true },
  { prop: "taskName", label: "任务名称", minWidth: "280", showOverflowTooltip: true },
  { prop: "taskTypeDesc", label: "任务类型", minWidth: "120", showOverflowTooltip: true },
  { prop: "startTime", label: "任务开始时间", minWidth: "180", showOverflowTooltip: true },
  { prop: "endTime", label: "任务结束时间", minWidth: "180", showOverflowTooltip: true },
  { prop: "factoryAreaDesc", label: "地块", minWidth: "120", showOverflowTooltip: true },
  { prop: "taskType", label: "状态", minWidth: "120", showOverflowTooltip: true },
  { prop: "checkGroupDesc", label: "巡检组", minWidth: "150", showOverflowTooltip: true },
  { prop: "submitTime", label: "最后执行时间", minWidth: "200", showOverflowTooltip: true }
]);
watch(
  () => isDetail.value,
  async () => {
    if (isDetail.value) {
      if (!planNo.value) {
        backMainPage();
        return;
      } else {
        let detail: { [key in string] } = await getByPlanNo({ planNo: planNo.value });
        detail.execType = String(detail.execType);
        const { checkRuleList, eqpList, checkAreaDesc, cycleTime } = detail as any;
        queryParams.value.planNo = planNo.value as string;
        queryTable();
        tableData.value = checkRuleList?.length > 0 ? checkRuleList : [];
        tableEqiupSelected.value = eqpList?.length > 0 ? eqpList : [];
        detailData.value = detail;
        if (checkAreaDesc) {
          checkAreaDescArr.value = checkAreaDesc.split(",");
        }
        if (cycleTime) {
          const arr = cycleTime.split(",").sort((a, b) => a - b);
          operates.value = arr.reduce((pre, cur) => {
            return [...pre, operateTimeArr[cur]];
          }, []);
        }
      }
    } else {
      planNo.value = "";
    }
  }
);
function reset() {
  detailData.value = cloneDeep(detailDataTmpl);
  weeks.value = [];
  days.value = [];
  months.value = [];
  operates.value = [];
  checkAreaDescArr.value = [];
  activeName.value = "first";
}
function backMainPage() {
  isDetail.value = false;
  isMain.value = true;
  planNo.value = "";
  reset();
}
function handelTabSelected(selectName) {
  activeName.value = selectName;
}
function editPlan() {
  const row = detailData.value;
  const { planNo: planNumber, planStatus } = row;
  planNo.value = planNumber;
  isDetail.value = false;
  if ([1, 2].indexOf(planStatus) !== -1) {
    isAdd.value = true;
  } else {
    isMain.value = true;

    isUpdate.value = true;
  }
}
function resetTime() {
  weeks.value = [];
  days.value = [];
  months.value = [];
}
function dealExecTime() {
  resetTime();
  if (detailData.value.cyclePerUnit === "YEAR") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}年的`;
    }
  } else if (detailData.value.cyclePerUnit === "HALF_YEAR") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}个半年的`;
    }
  } else if (detailData.value.cyclePerUnit === "QUARTER") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}季度的`;
    }
  } else if (detailData.value.cyclePerUnit === "DAY") {
    if (detailData.value.cyclePerNum) {
      return `每${detailData.value.cyclePerNum}天`;
    }
  } else if (detailData.value.cyclePerUnit === "WEEK") {
    if (detailData.value.cyclePerNum) {
      if (detailData.value.cycleValue) {
        let arr = detailData.value.cycleValue.split(",");
        // arr.forEach(item => {
        //   weeks.value.push(weeksMap[item]);
        // });

        Object.keys(weeksMap).forEach(item => {
          if (arr.includes(item)) {
            weeks.value.push(weeksMap[item]);
          }
        });
      }
      return `每${detailData.value.cyclePerNum}周的`;
    }
  } else if (detailData.value.cyclePerUnit === "MONTH") {
    if (detailData.value.cyclePerNum) {
      if (detailData.value.cycleValue) {
        let arr = detailData.value.cycleValue.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      return `每${detailData.value.cyclePerNum}月的`;
    }
  }
}
function scrollInit() {
  let routerName = "基本信息,巡检内容,执行周期,设备巡检";
  let routerRefs = [basicsRef, contentRef, periodRef, equipRef];
  routerList.value = routerName.split(",").map((item, index) => ({ ref: routerRefs[index], name: item }));
}
//右侧滚动导航相关函数
const handleScroll = debounce(({ scrollTop: curScrollTop }) => {
  console.log(scrollTop);
  scrollTop.value = curScrollTop;
}, 200);
onBeforeMount(() => {
  scrollInit();
});
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await queryTaskTable(params);
  taskTable.value = data?.data;
  total.value = data?.total;
};
const handleView = (row: any) => {
  let path = `/erc/inspect/task`;
  router.push({
    path: path,
    query: { reffer: "plan", taskNo: row.taskNo }
  });
};
</script>
<style lang="scss" scoped>
@import url("../../scss/view-detail.scss");
.view-plan-item {
  flex-grow: 1;
}
</style>
